package com.itic.mall.system.msg.phonesend.service;

import com.itic.appbase.framework.common.basevo.ReturnVo;
import com.itic.appbase.framework.common.service.CrudService;
import com.itic.appbase.framework.utils.StringHelper;
import com.itic.mall.system.inter.msg.phonesend.persistence.dao.PhoneSendDao;
import com.itic.mall.system.inter.msg.phonesend.persistence.model.PhoneSend;
import com.itic.mall.system.inter.msg.phonesend.persistence.model.PhoneSendExample;
import com.itic.mall.system.inter.users.usersmall.persistence.model.UsersMall;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


@Service
@Transactional
public class PhoneSendService
     extends CrudService<PhoneSendDao,PhoneSend,PhoneSendExample> {
    
	@Autowired
    private PhoneSendDao phoneSendDao;


	 public String sendPwd( UsersMall user, String pwd ){
	    	//先用华信发送，如果不成功，用维信发送
	    	PhoneSend phoneSend = new PhoneSend();
	    	ReturnVo returnVo = new ReturnVo();
	    	//	欢迎加入友惠家，请牢记您的信息，登入手机号码：【变量】，密码：【密码】。
	    	String text = "欢迎加入友惠家，请牢记您的信息，登入手机号码："+user.getUserPhone()+"，密码："+pwd+"。";
	    	if( StringHelper.isNotBlank(user.getUserPhone()) ){
	    		returnVo = sendMsgByHuaxin(user.getUserPhone(),text);
	    		if( !returnVo.getStatus().equals(SUCCESS) ){
	    			String returnMsg = returnVo.getReturnMsg();
	    			returnVo = sendMsgByWeixin(user.getUserPhone(), text);
	    			returnVo.setReturnMsg(returnMsg+returnVo.getReturnMsg());
	    		}
	    		phoneSend.setPhone(user.getUserPhone());
	    	}else{
	    		phoneSend.setPhone("用户未设置手机号码");
	    	}
	    	phoneSend.setSendText(text);
	    	
	    	phoneSend.setStatus(returnVo.getStatus());
	    	phoneSend.setReturnMsg(returnVo.getReturnMsg());
	    	
	    	this.initDefalutFields(phoneSend);
	    	phoneSendDao.insert(phoneSend);
	    	
	    	return phoneSend.getStatus();
	    }
	
    public String send( UsersMall user, String text ){
    	
    	//先用华信发送，如果不成功，用维信发送
    	PhoneSend phoneSend = new PhoneSend();
    	ReturnVo returnVo = new ReturnVo();
    	if( StringHelper.isNotBlank(user.getUserPhone()) ){
    		returnVo = sendMsgByHuaxin(user.getUserPhone(),text);
    		if( !returnVo.getStatus().equals(SUCCESS) ){
    			String returnMsg = returnVo.getReturnMsg();
    			returnVo = sendMsgByWeixin(user.getUserPhone(), text);
    			returnVo.setReturnMsg(returnMsg+returnVo.getReturnMsg());
    		}
    		phoneSend.setPhone(user.getUserPhone());
    	}else{
    		phoneSend.setPhone("用户未设置手机号码");
    	}
    	phoneSend.setSendText(text);
    	
    	phoneSend.setStatus(returnVo.getStatus());
    	phoneSend.setReturnMsg(returnVo.getReturnMsg());
    	
    	this.initDefalutFields(phoneSend);
    	phoneSendDao.insert(phoneSend);
    	
    	return phoneSend.getStatus();
    }
    
    /**
     * 通过华信平台发送短信给用户，（短信内容需要先设置模板）
     * @param phone
     * @param text
     * @return
     */
    public ReturnVo sendMsgByHuaxin( String phone,String text ){
    	ReturnVo returnVo = new ReturnVo();
    	returnVo.setStatus(FAILED);
		try {
			String Url="http://dx.ipyy.net/sms.aspx";
			
			HttpClient client=new HttpClient();
					
			PostMethod post=new PostMethod(Url);
			post.setRequestHeader("Content-type", "application/x-www-form-urlencoded;charset=utf-8");
			NameValuePair userid=new NameValuePair("userid","53772");
			NameValuePair account=new NameValuePair("account","yhjapp");
			NameValuePair password=new NameValuePair("password","123456789");
			NameValuePair mobile=new NameValuePair("mobile",phone);
			NameValuePair content=new NameValuePair("content",text);
			NameValuePair sendTime=new NameValuePair("sendTime","");
			NameValuePair action=new NameValuePair("action","send");
			NameValuePair extno=new NameValuePair("extno","");
			post.setRequestBody(new NameValuePair[]{userid,account,password,mobile,content,sendTime,action,extno});
			int statu=client.executeMethod(post);
			System.out.println("statu="+statu);
			String str=post.getResponseBodyAsString();
			
			//System.out.println(str);
			
			//将字符转化为XML
			Document doc=DocumentHelper.parseText(str);
			//获取根节点
			Element rootElt=doc.getRootElement();
			//获取根节点下的子节点的值
			String returnstatus=rootElt.elementText("returnstatus").trim();
			String message=rootElt.elementText("message").trim();
			String remainpoint=rootElt.elementText("remainpoint").trim();
			//String taskID=rootElt.elementText("taskID").trim();
			//String successCounts=rootElt.elementText("successCounts").trim();
			
			//System.out.println("返回状态为"+returnstatus);
			//System.out.println("返回信息提示："+message);
			//System.out.println("返回余额："+remainpoint);
			//System.out.println("返回任务批次："+taskID);
			//System.out.println("返回成功条数："+successCounts);
			if(returnstatus.equals("Success")){
				returnVo.setStatus(SUCCESS);
				returnVo.setReturnMsg("华信：短信还有"+remainpoint+"条短信");
			}else{
				returnVo.setStatus(FAILED);
				returnVo.setReturnMsg("华信："+message);
			}	
				
		} catch (Exception e) {
			returnVo.setReturnMsg(e.getMessage());
		}
		return returnVo;
    }
    
    
    /**
     * 通过维信平台发送短信给用户，（短信内容需要先设置模板）
     * @param telphone  手机号码
     * @return
     */
    public ReturnVo sendMsgByWeixin(String telphone,String text){
    	ReturnVo returnVo = new ReturnVo();
    	returnVo.setStatus(FAILED);
    	
    	HttpClient client = new HttpClient(); 
		PostMethod method = new PostMethod("http://120.55.205.5/webservice/sms.php?method=Submit"); 
			
		//client.getParams().setContentCharset("GBK");		
		client.getParams().setContentCharset("UTF-8");
		method.setRequestHeader("ContentType","application/x-www-form-urlencoded;charset=UTF-8");

	    //String content = new String("您的验证码是："+codeCont+"。请不要把验证码泄露给其他人。"); 
	    String content = new String(text);
	    NameValuePair[] data = {//提交短信
	    		 new NameValuePair("account", "C11714710"), 
			     new NameValuePair("password", "85202a35086eb358e717dbf9ebc6e9bc"), //密码可以使用明文密码或使用32位MD5加密
			    //new NameValuePair("account", "99911547"), 
		    //new NameValuePair("password", "a123456"), //密码可以使用明文密码或使用32位MD5加密
			    //new NameValuePair("password", util.StringUtil.MD5Encode("密码")),
			    new NameValuePair("mobile", telphone), 
			    new NameValuePair("content", content),
		};
		
		method.setRequestBody(data);		
		
		
		try {
			client.executeMethod(method);	
			 
			String SubmitResult =method.getResponseBodyAsString();
					
			//System.out.println(SubmitResult);

			Document doc = DocumentHelper.parseText(SubmitResult); 
			Element root = doc.getRootElement();


			String code = root.elementText("code");	
			String msg = root.elementText("msg");	
			//String smsid = root.elementText("smsid");	
			
			
			//System.out.println(code);
			//System.out.println(msg);
			//System.out.println(smsid);
						
			if("2".equals(code)){
				returnVo.setStatus(SUCCESS);
				returnVo.setReturnMsg("维信："+msg);
			}else{
				returnVo.setReturnMsg("维信："+msg);
			}
			
		} catch (Exception e) {
			returnVo.setReturnMsg(e.getMessage());
		}	
 		return returnVo;
    }
}